﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 可序列化字典数据, 需要被继承使用才能序列化
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
[System.Serializable]
public abstract class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{
    [SerializeField]
    private List<TKey> keys = new List<TKey>();
    [SerializeField]
    private List<TValue> values = new List<TValue>();

    /// <summary>
    /// 转为普通的字典类型
    /// </summary>
    /// <returns></returns>
    public Dictionary<TKey, TValue> ToDictionary()
    {
        var dic = new Dictionary<TKey, TValue>();
        for (int i = 0; i < keys.Count; i++)
        {
            var key = keys[i];
            dic.Add(key, values[i]);
        }
        return dic;
    }

    public void OnBeforeSerialize()
    {
        keys.Clear();
        values.Clear();
        keys.Capacity = this.Count;
        values.Capacity = this.Count;
        foreach (var kvp in this)
        {
            keys.Add(kvp.Key);
            values.Add(kvp.Value);
        }
    }

    public void OnAfterDeserialize()
    {
        this.Clear();
        int count = Mathf.Min(keys.Count, values.Count);
        for (int i = 0; i < count; ++i)
        {
            this.Add(keys[i], values[i]);
        }
    }
}